<template>
  <div class="app-container">
    <el-form :model="hospset" :rules="rules" ref="hospset" label-width="120px">
      <el-form-item label="医院名称" prop="hosname">
        <el-input v-model="hospset.hosname" />
      </el-form-item>
      <el-form-item label="医院编号" prop="hoscode">
        <el-input v-model="hospset.hoscode" />
      </el-form-item>
      <el-form-item label="api地址" prop="apiUrl">
        <el-input v-model="hospset.apiUrl" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactsName">
        <el-input v-model="hospset.contactsName" />
      </el-form-item>
      <el-form-item label="电话" prop="contactsPhone">
        <el-input v-model="hospset.contactsPhone" />
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate('hospset')">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import hospitalSet from "@/api/hospitalSet";

export default {
  data() {
    return {
      saveBtnDisabled: false,
      hospset: {},
      rules: {
        hosname: [
          { required: true, message: "请输入医院名称", trigger: "blur" },
        ],
        hoscode: [
          { required: true, message: "请输入医院编号", trigger: "blur" },
        ],
        apiUrl: [{ required: true, message: "请输入api地址", trigger: "blur" }],
        contactsName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        contactsPhone: [
          { required: true, message: "请输入电话", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //获取路由中的参数, 存入 hospset 对象中
    this.hospset.id = this.$route.params.id;
    if (this.hospset.id) {
      //修改进来时，会有id
      //查询医院设置的信息》数据回显
      this.getById(this.hospset.id);
    }
  },
  methods: {
    //根据id查询
    getById(id) {
      hospitalSet.getById(id).then((response) => {
        this.hospset = response.data.hospitalSet;
      });
    },
    //添加
    add() {
      //执行添加
      hospitalSet.add(this.hospset).then((response) => {
        this.$message.success("添加成功");

        //路由跳转到列表页面
        this.$router.push("/yygh/hospitalSet/list");
      });
    },
    //修改
    update(){
      //执行修改
      hospitalSet.update(this.hospset).then((response) => {
        this.$message.success("修改成功");

        //路由跳转到列表页面
        this.$router.push("/yygh/hospitalSet/list");
      });
    },
    //保存按钮,添加或修改
    saveOrUpdate(formName) {
      //表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //禁用保存按钮
          this.saveBtnDisabled = true;

          if (this.hospset.id) {
            //如果传递了id，执行修改
            this.update();
          } else {
            //没有传递id，执行添加
            this.add();
          }

          //启用保存按钮
          this.saveBtnDisabled = false;
        }
      });
    },
  },
};
</script>
